package com.muyan.sys.common.core.redis;

import com.muyan.sys.common.config.RedisSingleConfig;
import com.muyan.sys.common.utils.spring.SpringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.util.StringUtils;

public class RedissonConfig {

    // 单例实例
    private static volatile RedissonClient redissonClient;

    // 私有构造函数，防止外部实例化
    private RedissonConfig() {}

    public static synchronized RedissonClient getRedissonClient() {
        if (redissonClient == null) {

                if (redissonClient == null) {
                    RedisSingleConfig redisConfig=    SpringUtils.getBean(RedisSingleConfig.class);
                    // 配置 Redis
                    Config config = new Config();
                   String address= String.format("redis://%s:%s", redisConfig.getHost(), redisConfig.getPort());
                    SingleServerConfig serverConfig = config.useSingleServer()
                            .setAddress(address)
                            .setTimeout(redisConfig.getTimeouts())
                            .setPingConnectionInterval(redisConfig.getPingTimeout())
                            .setRetryInterval(redisConfig.getRetryInterval())
                            .setConnectionPoolSize(redisConfig.getConnectionPoolSize())
                            .setConnectionMinimumIdleSize(redisConfig.getConnectionMinimumIdleSize());

                    if(StringUtils.hasLength(redisConfig.getPassword())) {
                        serverConfig.setPassword(redisConfig.getPassword());
                    }



                    redissonClient = Redisson.create(config);

            }
        }
        return redissonClient;
    }
}
